<template>
  <div>
    <a-button @click="openModal" >增加</a-button>
    <a-button @click="deleteId">删除</a-button>
  <a-table 
    :columns="columns" 
    :data-source="dataSource" 
    :row-selection="rowSelection" 
    :row-key="record => record.id"
    :scroll="{ y: 550 }"
    bordered 
    class="editable-table"
  >
    <template #bodyCell="{ column, text, record }">
      <template v-if="['name', 'studentNumber', 'password', 'telephone', 'mail'].includes(column.dataIndex)">
        <div class="editable-cell">
          <a-input
            v-if="editableData[record.id]"
            v-model:value="editableData[record.id][column.dataIndex]"
            class="input-cell"
          />
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
      <template v-else-if="column.dataIndex === 'operation'">
        <div class="editable-row-operations">
          <span v-if="editableData[record.id]">
            <a-typography-link @click="save(record.id)">保存</a-typography-link>
            <a-popconfirm title="确定取消?" @confirm="cancel(record.id)" okText="确定" cancelText="取消">
              <a>取消</a>
            </a-popconfirm>
          </span>
          <span v-else>
            <a @click="edit(record.id)">编辑</a>
          </span>
        </div>
      </template>
    </template>
  </a-table>
  <studentAdd :open="isModalOpen" @update:open="isModalOpen = $event" @add="refreshData" />
</div>
 
</template>

<script setup>
import { cloneDeep } from 'lodash-es';
import { onMounted, reactive, ref } from 'vue';
import  studentAdd from '@/components/addStudent.vue'
import { updateStudent, getListBreak,deleteStudent,batchDeleteStudent } from '@/api/studentApi';
onMounted(() => {
  fetchData();
});
const selectedRowKeys=ref([]);
const fetchData = () => {
  getListBreak().then(res => {
    dataSource.value = res.data;
  });
};
const isModalOpen = ref(false);

const openModal = () => {
  isModalOpen.value = true;
};
const refreshData = () => {
  fetchData();
};
const deleteId = () => {
  const selectedRows = dataSource.value.filter(item => selectedRowKeys.value.includes(item.id));
  console.log('即将删除的行:', selectedRows);

  if (selectedRows.length > 1) {
    // 如果选择的行数大于1，使用批量删除
    const selectedIds = selectedRows.map(item => item.id);
    console.log('批量删除学生 ID:', selectedIds);
    
    // 调用批量删除接口
    batchDeleteStudent(selectedIds)
      .then(results => {
        console.log('批量删除成功:', results);
        refreshData(); // 删除后刷新数据
      })
      .catch(error => {
        console.error('批量删除失败:', error);
      });
  } else if (selectedRows.length === 1) {
    // 如果只选择了一行，使用单个删除
    const selectedId = selectedRows[0].id;
    console.log(`正在删除学生 ID: ${selectedId}`);
    
    deleteStudent(selectedId)
      .then(results => {
        console.log('删除成功:', results);
        refreshData(); // 删除后刷新数据
      })
      .catch(error => {
        console.error('删除失败:', error);
      });
  } else {
    console.error('没有选择任何行进行删除');
  }
};

const columns = [
  { title: '姓名', dataIndex: 'name', width: '10%' },
  { title: '学号', dataIndex: 'studentNumber', width: '15%' },
  { title: '密码', dataIndex: 'password', width: '15%' },
  { title: '手机号', dataIndex: 'telephone', width: '15%' },
  { title: '邮件', dataIndex: 'mail', width: '15%' },
  { title: '违纪次数', dataIndex: 'breakTheRuleCount', width: '15%' },
  { title: '操作', dataIndex: 'operation' },
];

const data = [];
const dataSource = ref(data);
const editableData = reactive({});

const edit = id => {
  editableData[id] = cloneDeep(dataSource.value.find(item => id === item.id));
};

const save = id => {
  const updatedRecord = Object.assign(dataSource.value.find(item => id === item.id), editableData[id]);
  console.log(updatedRecord);

  // 调用接口更新学生信息
  updateStudent(updatedRecord)
    .then(() => {
      delete editableData[id];
      console.log('学生修改成功');
    })
    .catch(error => {
      console.error('学生修改失败:', error);
    });
};

const cancel = id => {
  delete editableData[id];
};

const rowSelection = ref({
  onChange: (keys, selectedRows) => {
    selectedRowKeys.value = keys; // 更新选中的行
    console.log(`selectedRowKeys: ${keys}`, 'selectedRows: ', selectedRows);
  },
  getCheckboxProps: record => ({
    disabled: record.name === 'Disabled User',
    name: record.name,
  }),
});


</script>

<style scoped>
.editable-row-operations a {
  margin-right: 8px;
}
.input-cell {
  margin: -5px 0;
}
</style>
